<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Login extends CI_Controller
{
    function __construct()
    {
        parent::__construct();

    }

    public function index()
    {
        $this->load->library('encrypt');
        $username = $this->input->post('username');
        $password = $this->input->post('password');
        $error = array();
        if(empty($username))
        {
            response_json([],'101','请输入账号!');
        }
        if(empty($password))
        {
            response_json([],'101','请输入密码!');
        }
        if(empty($error))
        {
            $row = (array)$this->db->where(array('admin_name'=>$username, 'status'=>1))->get('admin')->row_array();
            if(empty($row) || empty($row['admin_salt']))
            {
                response_json([],'101','账号密码错误!');
            }
            if(md5(md5($password).$row['admin_salt']) != $row['admin_pwd'])
            {
                response_json([],'101','账号密码错误!');
            }
        }

        //加载对应权限菜单
        $this->load->model('admin_group_model');
        $menu = $this->admin_group_model->load_menu($row['group_id']);
        if(empty($menu))
        {
            response_json([],'101','您的权限不足以登录后台!');
        }
        //取得第一个菜单连接
        $link = current($menu);
        if(empty($link['jump']) && !empty($link['list']))
        {
            $link = current($link['list']);
        }
        $jump = site_url($link['jump']);

        $this->db->update('admin', array('admin_auth'=>md5(intval($row['admin_id']).time().rand(0,9)), 'logip'=>getip(), 'logtime'=>date('Y-m-d H:i:s')), array('admin_id'=>$row['admin_id']));
        // 生成token
        $token = $this->encrypt->encode($row['admin_id'].":".$username.":".time().":".$row['group_id']);
        @session_start();
        $_SESSION['admin_id']   = intval($row['admin_id']);
        $_SESSION['access_token']   = $token;
        $_SESSION['admin_auth'] = md5($_SESSION['admin_id'].time().rand(0,9));
        $data['jump'] = $jump;
        $data['access_token'] = $token;
        return response_json($data,'0','登录成功!');

    }
}